package com.supor.aiot.common.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Build;
import android.text.TextUtils;

import com.android.baseconfig.common.utils.Logc;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WifiStationManager {
    private static final String TAG = "WifiStation";

    public static final int WIFI_CONNECTED = 0x01;
    public static final int WIFI_CONNECT_FAILED = 0x02;
    public static final int WIFI_CONNECTING = 0x03;

    private WifiManager mWifiManager = null;
    private Context mContext = null;
    private static WifiStationManager instance = null;

    /**
     * 定义几种加密方式，一种是WEP，一种是PSK，还有没有密码的情况
     *
     * @author lee
     */
    public enum WifiCipherType {
        WIFICIPHER_NOPASS, WIFICIPHER_WEP, WIFICIPHER_PSK, WIFICIPHER_INVALID
    }


    /**
     * 单例
     */
    public static WifiStationManager initInstance(Context context) {
        if (null == instance) {
            instance = new WifiStationManager(context);
        }
        return instance;
    }

    public static WifiStationManager getInstance() {
        return instance;
    }

    private WifiStationManager(Context mContext) {
        this.mContext = mContext;
        mWifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    /***************************** interface ****************************************/

    /**
     * 获取当前WiFi的SSID；
     *
     * @return 若WiFi已连接则返回当前WiFi的SSID，否则返回null；
     */
    public String getCurrentWifiSSID() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                WifiInfo mWifiInfo = getConnectionWifiInfo();
                if (mWifiInfo == null) {
                    mWifiInfo = mWifiManager.getConnectionInfo();
                }
                String ssid = null;

                if (Build.VERSION.SDK_INT <= 26 || Build.VERSION.SDK_INT > 28) {
                    if (mWifiInfo != null) {
                        ssid = mWifiInfo.getSSID();
                    }
                } else if (Build.VERSION.SDK_INT == 28) {
                    if (mWifiInfo != null) {
                        int networkId = mWifiInfo.getNetworkId();
                        @SuppressLint("MissingPermission")
                        List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();

                        if (netConfList != null) {
                            for (WifiConfiguration wificonf : netConfList) {
                                if (wificonf.networkId == networkId) {
                                    ssid = wificonf.SSID;
                                }
                            }
                        }

                    }
                }
                if (TextUtils.isEmpty(ssid) || "<unknown ssid>".equalsIgnoreCase(ssid) || Build.VERSION.SDK_INT == Build.VERSION_CODES
                        .O_MR1) {
                    if (mContext != null) {
                        ConnectivityManager connManager =
                                (ConnectivityManager) mContext.getApplicationContext()
                                .getSystemService(Context.CONNECTIVITY_SERVICE);
                        assert connManager != null;
                        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
                        if (networkInfo != null && networkInfo.isConnected()) {
                            if (networkInfo.getExtraInfo() != null) {
                                String routerWifiSsid = networkInfo.getExtraInfo().replace("\"",
                                        "");
                                return filterQuotedString(routerWifiSsid);
                            }
                        }
                    }
                }

                if (ssid != null) {
                    return filterQuotedString(ssid);
                }
            }
        }
        return null;
        // WifiInfo wifiInfo = getConnectionWifiInfo();
        // if(null == wifiInfo) {
        // 	return null;
        // }
        //
        // return filterQuotedString(wifiInfo.getSSID());
    }

    /**
     * 获取当前WiFi的BSSID；
     *
     * @return 若WiFi已连接则返回当前WiFi的BSSID，否则返回null；
     */
    public String getCurrentWifiBSSID() {
        WifiInfo wifiInfo = getConnectionWifiInfo();
        return (wifiInfo == null) ? null : wifiInfo.getBSSID();
    }

    /**
     * 获取本地IP地址，Android版本需高于4.0；
     *
     * @return 若WiFi已连接并且Android版本高于4.0则返回本地IP地址，否则返回null；
     */
    public String getCurrentIpAddress() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return null;
        } else {
            WifiInfo wifiInfo = getConnectionWifiInfo();
            return (wifiInfo == null) ? null : intToIp(wifiInfo.getIpAddress());
        }
    }

    /**
     * 获取本地MAC地址；
     *
     * @return 若WiFi已连接则返回本地MAC地址，否则返回null；
     */
    public String getWifiMacAddress() {
        WifiInfo wifiInfo = getConnectionWifiInfo();
        return (wifiInfo == null) ? null : wifiInfo.getMacAddress();
    }

    /**
     * 获取本地网关地址，Android版本需高于4.0；
     *
     * @return 若WiFi已连接并且Android版本高于4.0则返回本地网关地址，否则返回null；
     */
    public String getGatewayAddress() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return null;
        } else {
            if (null != mWifiManager) {
                return intToIp(mWifiManager.getDhcpInfo().gateway);
            }
        }
        return null;
    }

    /**
     * 获取当前WiFi的networkId
     *
     * @return 若WiFi已连接则返回当前WiFi的networkId，否则返回-1
     */
    public int getNetworkId() {
        WifiInfo wifiInfo = getConnectionWifiInfo();
        return (wifiInfo == null) ? -1 : wifiInfo.getNetworkId();
    }

    /**
     * 创建wifi锁；
     *
     * @param name wifi锁名；
     * @return MulticastLock对象；
     */
    public MulticastLock createWifiMulticastLock(String name) {
        if (null != mWifiManager) {
            return mWifiManager.createMulticastLock(name);
        }

        return null;
    }

    /**
     * 获得本地网络广播地址；
     *
     * @return 若WiFi已连接则返回本地网络广播地址，否则返回null；
     */
    @SuppressWarnings("unused")
    private String getBroadcastAddress() {
        if (null != mWifiManager) {
            DhcpInfo myDhcpInfo = mWifiManager.getDhcpInfo();
            if (myDhcpInfo == null) {
                Logc.e(TAG, "Could not get broadcast address");
                return null;
            }
            int broadcast = (myDhcpInfo.ipAddress & myDhcpInfo.netmask) | ~myDhcpInfo.netmask;
            byte[] quads = new byte[4];
            for (int k = 0; k < 4; k++) {
                quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
            }
            try {
                return InetAddress.getByAddress(quads).toString();
            } catch (UnknownHostException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 根据指定的WifiConfiguration对象来连接WiFi，不会创建新的WifiConfiguration对象，调用会阻塞；
     *
     * @param config 原来连接成功的WifiConfiguration对象；
     * @return 连接成功返回true，否则返回false；
     */
    synchronized public boolean connectWifi(WifiConfiguration config) {
        return connect(filterQuotedString(config.SSID));
    }

    /**
     * 连接指定路由器，需要密码，调用会阻塞；
     *
     * @param SSID 路由器SSID；
     *             password 路由器密码；
     * @return 连接成功返回true，否则返回false
     */
    synchronized public boolean connectWifi(String SSID, String password) {
        ScanResult scanResult = getScanResult(SSID);
        if (null != scanResult) {
            return connectWifi(scanResult, password);
        }
        return false;
    }

    /**
     * 连接指定路由器，需要密码，调用会阻塞；
     *
     * @param scanResult 该路由器的scanResult对象；
     *                   password 路由器密码；
     * @return 连接成功返回true，失败返回false
     */
    synchronized public boolean connectWifi(ScanResult scanResult, String password) {
        return connectWifi(scanResult.SSID, password, getSecurity(scanResult));
    }

    /**
     * 连接指定路由器，需要密码和加密类型，调用会阻塞；
     *
     * @param SSID 路由器SSID；
     *             password 路由器密码；
     *             wifiCipherType 加密类型；
     * @return 连接成功返回true，失败返回false
     */
    synchronized public boolean connectWifi(String SSID, String password, WifiCipherType wifiCipherType) {
        if (SSID == null) {
            Logc.e(TAG, "SSID or password is invalid!");
            return false;
        }

        /** 如果WiFi关闭则打开WiFi */
        int retry = 10;
        while (!isWifiEnabled() && retry-- > 0) {
            openWifi();
            sleep(2000);
        }
        if (!isWifiEnabled()) {
            Logc.e(TAG, "open wifi failed");
            return false;
        }
        boolean status = false;
        retry = 1;
        do {
            connect(createWifiConfig(), SSID, password, wifiCipherType);
            int sleepTime = 30;
            while (sleepTime-- > 0) {
                sleep(200);
                status = isWifiConnected();
                if (status) {
                    String currentSSID = getCurrentWifiSSID();
                    if (null != currentSSID) {
                        currentSSID = filterQuotedString(currentSSID);
                        if (currentSSID.equalsIgnoreCase(SSID)) {
                            status = true;
                            Logc.v(TAG, "connect " + SSID + " succeed!");
                            break;
                        }
                    }
                    status = false;
                }
            }
            if (sleepTime >= 0) {
                break;
            }
        } while (--retry > 0);

        return status;
    }

    /**
     * 判断WiFi是否已经打开
     *
     * @return 已经打开返回true，否则返回false
     */
    public boolean isWifiEnabled() {
        if (null != mWifiManager) {
            return mWifiManager.isWifiEnabled();
        }
        return false;
    }

    /**
     * 打开WiFi
     */
    public void openWifi() {
        if (null != mWifiManager) {
            if (!mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(true);
            }
        }
    }

    /**
     * 关闭WiFi
     */
    public void closeWifi() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(false);
            }
        }
    }

    /**
     * 断开当前连接的网络
     */
    public void disconnectWifi() {
        WifiInfo mWifiInfo = getConnectionWifiInfo();
        if (mWifiInfo != null) {
            // mWifiManager.disableNetwork(mWifiInfo.getNetworkId());
            mWifiManager.disconnect();
        }
    }

    public boolean startScan() {
        if (null != mWifiManager) {
            return mWifiManager.startScan();
        }
        return false;
    }

    /**
     * 获取ScanResult对象，会有2s延时;
     *
     * @return 若指定SSID对应的ScanResult对象存在则返回该对象，否则返回null;
     */
    public ScanResult getScanResult() {
        String SSID = getCurrentWifiSSID();
        if (null != mWifiManager) {
            mWifiManager.startScan();
            /** scan一次需要等待2s左右才能得到当前正确结果 */
            sleep(2000);
            List<ScanResult> mScanResultList = mWifiManager.getScanResults();
            if (null != mScanResultList) {
                for (ScanResult currentResult : mScanResultList) {
                    if (currentResult.SSID.equalsIgnoreCase(SSID)) {
                        return currentResult;
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取指定SSID对应的ScanResult对象，会有2s延时;
     *
     * @param SSID 路由器SSID；
     * @return 若指定SSID对应的ScanResult对象存在则返回该对象，否则返回null;
     */
    public ScanResult getScanResult(String SSID) {
        if (null == SSID) {
            return null;
        }

        removeNetworkConfig(SSID);

        List<ScanResult> mScanResultList = getScanResultList();
        if (null != mScanResultList) {
            for (ScanResult currentResult : mScanResultList) {
                if (currentResult.SSID.equalsIgnoreCase(SSID)) {
                    return currentResult;
                }
            }
        }

        return null;
    }

    /**
     * 获取当前网络的ScanResult列表，会有2s延时，务必在线程里调用;
     *
     * @return 当前网络的ScanResult列表;
     */
    public List<ScanResult> getScanResultList() {
        int retry = 10;
        while (!isWifiEnabled() && retry-- > 0) {
            openWifi();
            sleep(2000);
        }
        if (!isWifiEnabled()) {
            Logc.e(TAG, "open wifi failed");
            return null;
        }

        if (null != mWifiManager) {
            mWifiManager.startScan();
            /** scan一次需要等待2s左右才能得到当前正确结果 */
            sleep(2000);
            return mWifiManager.getScanResults();
        }

        return null;
    }

    /**
     * 获取当前网络的ScanResult列表，会有2s延时，务必在线程里调用;
     *
     * @param scan 是否扫描：扫描有2s延时
     * @return 当前网络的ScanResult列表;
     */
    public List<ScanResult> getScanResultList(boolean scan) {
        int retry = 10;
        while (!isWifiEnabled() && retry-- > 0) {
            openWifi();
            sleep(2000);
        }
        if (!isWifiEnabled()) {
            Logc.e(TAG, "open wifi failed");
            return null;
        }

        if (null != mWifiManager) {
            if (scan) {
                mWifiManager.startScan();
                /** scan一次需要等待2s左右才能得到当前正确结果 */
                sleep(2000);
            }
            return mWifiManager.getScanResults();
        }

        return null;
    }

    /**
     * 获取指定SSID对应的WifiConfiguration对象;
     *
     * @param SSID 路由器SSID；
     * @return 若指定SSID存在对应的WifiConfiguration对象则返回该对象，否则返回null;
     */
    public WifiConfiguration getWifiConfig(String SSID) {
        if (null != mWifiManager) {
            @SuppressLint("MissingPermission") List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
            if (null != existingConfigs && existingConfigs.size() > 0) {
                for (WifiConfiguration existingConfig : existingConfigs) {
                    if (existingConfig.SSID.equalsIgnoreCase("\"" + SSID + "\"")) {
                        return existingConfig;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取WifiConfiguration列表;
     *
     * @return WifiConfiguration列表;
     */
    public List<WifiConfiguration> getWifiConfigurationList() {
        if (null != mWifiManager) {
            @SuppressLint("MissingPermission") List<WifiConfiguration> wifiConfigurationList = mWifiManager.getConfiguredNetworks();
            return wifiConfigurationList;
        }

        return null;
    }

    /**
     * 判断MOBILE网络 GPRS,3G是否可用;
     *
     * @return 连接可用返回true，否则返回false;
     */
    public boolean isMobileNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (networkInfo != null && networkInfo.isAvailable()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断WiFi网络是否可用;
     *
     * @return 连接可用返回true，否则返回false;
     */
    public boolean isWifiNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (networkInfo != null && networkInfo.isAvailable()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断WiFi是否连接成功;
     *
     * @return 连接成功返回true，失败返回false;
     */
    public boolean isWifiConnected() {
        if (getWifiStatus() == WIFI_CONNECTED) {
            return true;
        }

        return false;
    }

    /**
     * 判断路由器是否连接需要密码,是否安全；
     *
     * @return 需要返回true，不需要返回false
     */
    public boolean isWifiSecurity(ScanResult scanResult) {
        if (getSecurity(scanResult) == WifiCipherType.WIFICIPHER_NOPASS) {
            return false;
        }
        return true;
    }

    /****************************************************************************************/
    /**
     * 获取当前WiFi的WifiInfo对象；
     *
     * @return 若WiFi已连接则返回当前WiFi的WifiInfo对象，否则返回null；
     */
    public WifiInfo getConnectionWifiInfo() {
        if (null != mWifiManager) {
            if (isWifiEnabled() && isWifiConnected()) {
                return mWifiManager.getConnectionInfo();
            }
        }
        return null;
    }

    /**
     * 获取WIFI当前连接状态；
     *
     * @return CONNECTED返回1，DISCONNECTED返回2，CONNECTING返回3，其余返回4；
     */
    private int getWifiStatus() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
            return 0x1;
        } else if (wifiNetworkInfo.getDetailedState() == DetailedState.DISCONNECTED) {
            return 0x2;
        } else if (wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
            return 0x3;
        } else {
            return 0x4;
        }
    }

    /**
     * 根据指定SSID连接网络，如果存在指定的WiFiConfiguration对象则直接进行连接，不创建新WiFiConfiguration对象；
     *
     * @param SSID 路由器ssid；
     * @return 如果存在指定的WiFiConfiguration对象并且连接成功返回true，否则返回false；
     */
    private boolean connect(String SSID) {
        WifiConfiguration wifiConfiguration = getWifiConfig(SSID);

        if (wifiConfiguration != null) {
            WifiInfo wifiInfo = getConnectionWifiInfo();
            if (null != wifiInfo && wifiInfo.getSSID().equalsIgnoreCase(filterQuotedString(wifiConfiguration.SSID))) {
                mWifiManager.disableNetwork(wifiConfiguration.networkId);
            }

            if (!mWifiManager.enableNetwork(wifiConfiguration.networkId, true)) {
                Logc.d(TAG, "enable network failed! SSID = " + wifiConfiguration.SSID);
                return false;
            }

            boolean status = false;
            int retry = 5;
            do {
                sleep(3000);
                status = isWifiConnected();

                if (status) {
                    String currentSSID = getCurrentWifiSSID();
                    if (null != currentSSID) {
                        currentSSID = filterQuotedString(currentSSID);
                        if (currentSSID.equalsIgnoreCase(filterQuotedString(wifiConfiguration.SSID))) {
                            status = true;
                            Logc.v(TAG, "wifi connect succeed!");
                            break;
                        }
                    }
                    status = false;
                }
            } while (--retry > 0);

            return status;
        }
        return false;
    }

    /**
     * 按照WiFiConfiguration进行连接
     *
     * @param config 新new 的WiFiConfiguration对象；
     *               SSID 路由器ssid；
     *               password 路由器密码；
     *               security 路由器加密类型；
     */
    private void connect(WifiConfiguration config, String SSID, String password, WifiCipherType security) {
        config.SSID = convertToQuotedString(SSID);
        config.hiddenSSID = true;

        if (security == WifiCipherType.WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(KeyMgmt.NONE);
        } else if (security == WifiCipherType.WIFICIPHER_WEP) {
            config.allowedKeyManagement.set(KeyMgmt.NONE);
            config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
            if (password.length() != 0) {
                int length = password.length();
                /** WEP-40, WEP-104, and 256-bit WEP (WEP-232?) */
                if ((length == 10 || length == 26 || length == 58)
                        && password.matches("[0-9A-Fa-f]*")) {
                    config.wepKeys[0] = password;
                } else {
                    config.wepKeys[0] = '"' + password + '"';
                }
            }
        } else if (security == WifiCipherType.WIFICIPHER_PSK) {
            config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
            if (password.length() != 0) {
                if (password.matches("[0-9A-Fa-f]{64}")) {
                    config.preSharedKey = password;
                } else {
                    config.preSharedKey = '"' + password + '"';
                }
            }
        }

        connectWithWifiConfiguration(config);
    }

    /**
     * 使用新创建的WiFiConfiguration来连接网络，会删除旧的WifiConfiguration配置；
     *
     * @param wcg
     */
    private void connectWithWifiConfiguration(WifiConfiguration wcg) {
        if (null != mWifiManager) {
            /** WifiConfiguration存在的话先删掉，不然WifiConfiguration列表会一直增加 */
            // removeNetworkConfig(filterQuotedString(wcg.SSID));

            int wcgID = mWifiManager.addNetwork(wcg);
            if (wcgID != -1) {
                if (!mWifiManager.enableNetwork(wcgID, true)) {
                    Logc.e(TAG, "enable network failed");
                }
            } else {
                Logc.e(TAG, "add network failed");
            }
        }
    }

    /**
     * 创建一个新的网络配置
     *
     * @return
     */
    private WifiConfiguration createWifiConfig() {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        return config;
    }

    /**
     * 删除一个网络配置；
     *
     * @param SSID 路由器ssid；
     */
    public void removeNetworkConfig(String SSID) {
        if (null != mWifiManager) {
            WifiConfiguration tempConfig = getWifiConfig(SSID);
            if (tempConfig != null) {
                boolean result = mWifiManager.removeNetwork(tempConfig.networkId);
                Logc.d("removeWifiConfig  result:" + result);
                mWifiManager.saveConfiguration();

            }
        }
    }

    /**
     * 获取路由器加密类型；
     *
     * @param result 路由器ScanResult对象；
     */
    private WifiCipherType getSecurity(ScanResult result) {
        if (result.capabilities.contains("WEP")) {
            return WifiCipherType.WIFICIPHER_WEP;
        } else if (result.capabilities.contains("PSK")) {
            return WifiCipherType.WIFICIPHER_PSK;
        }
        return WifiCipherType.WIFICIPHER_NOPASS;
    }


    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 过滤掉字符串两端的双引号
     *
     * @param ssid
     * @return 过滤掉两端双引号的string
     */
    private String filterQuotedString(String ssid) {
        int strLength = ssid.length();

        if (null == ssid || 0 == strLength) {
            return null;
        }

        if (String.valueOf(ssid.charAt(0)).equals("\"")
                && String.valueOf(ssid.charAt(strLength - 1)).equals("\"")) {
            return ssid.substring(1, strLength - 1);
        }
        return ssid;
    }

    /**
     * 在字符串两端添加双引号
     *
     * @param ssid
     * @return 添加双引号的string
     */
    private String convertToQuotedString(String ssid) {
        return "\"" + ssid + "\"";
    }

    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }


    public static boolean is24GHzWifi(int frequency) {
        return frequency > 2400 && frequency < 2500;
    }

    public static boolean is5GHzWifi(int frequency) {
        return frequency > 4900 && frequency < 5900;
    }

    /**
     * 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     *
     * @return
     */
    public static boolean ping(String ipAddress, int pingTimes, int timeOut) {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -W 2 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            Logc.d("------ping-----");
            InputStream input = p.getInputStream();
            Logc.d("------ping2-----");
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                Logc.d("------ping3-----");
                stringBuffer.append(content);
            }
            Logc.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Logc.d("----result---", "result = " + result);
        }
        return false;
    }

    public static boolean ping2(String ipAddress, int pingTimes, int timeOut) {
        BufferedReader in = null;
        Runtime r = Runtime.getRuntime(); // 将要执行的ping命令,此命令是windows格式的命令
        Process p = null;
        // String pingCommand = "ping " + "-c " + pingTimes  + " -W " + timeOut + " " + ipAddress;
        String pingCommand = "ping "  + " -w " + timeOut + " " + ipAddress;
        try {  // 执行命令并获取输出
            System.out.println(pingCommand);
            p = r.exec(pingCommand);
            // Logc.d("----ping---", " = " );
            if (p == null) {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));  // 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
            int connectedCount = 0;
            String line = null;
            while ((line = in.readLine()) != null) {
                // Logc.d("----ping---", "line = " + line);
                if (getCheckResult(line) == 1) {
                    return true;
                }
                // connectedCount += getCheckResult(line);
            }  // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
            return connectedCount == pingTimes;
        } catch (Exception ex) {
            ex.printStackTrace();  // 出现异常则返回假
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (p != null) {
                    p.destroy();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 不靠谱
     * @param ipAddress
     * @param pingTimes
     * @param timeOut
     * @return
     * @deprecated
     */
    public static boolean ping3(String ipAddress, int pingTimes, int timeOut) {
        try {
            if (InetAddress.getByName(ipAddress).isReachable(timeOut)) {
                Logc.d("morse", "pingNet onSuccess");
                return true;
            } else {
                Logc.d("morse", "pingNet onFailure");
                if (pingTimes != 100) {
                    ping3("202.108.22.5", 100, 1000);
                }
            }
        } catch (Throwable e) {
            Logc.d("", e);
        }
        return false;
    }

    //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
    private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
        Pattern pattern = Pattern.compile("(ttl=\\d+)",  Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line.toLowerCase());
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }

    public static String getInetAddress(String host) {
        String IPAddress = "";
        InetAddress inetAddress = null;
        try {
            if (host == null) {
                inetAddress = InetAddress.getLocalHost();
            } else {
                inetAddress = InetAddress.getByName(host);
            }
            IPAddress = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return IPAddress;
        }
        return IPAddress;
    }

    /**
     * 获取外网IP地址
     *
     * @return IP
     */
    public static String getOutNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,
                        StandardCharsets.UTF_8));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;
    }

    public static final int WIFI_AP_STATE_DISABLING = 10;
    public static final int WIFI_AP_STATE_DISABLED = 11;
    public static final int WIFI_AP_STATE_ENABLING = 12;
    public static final int WIFI_AP_STATE_ENABLED = 13;
    public static final int WIFI_AP_STATE_FAILED = 14;

    public int getWifiApState(Context mContext) {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApState");
            int i = (Integer) method.invoke(wifiManager);
            Logc.i(TAG,"wifi state: " + i);
            return i;
        } catch (Exception e) {
            Logc.e(TAG,"Cannot get WiFi AP state" + e);
            return WIFI_AP_STATE_FAILED;
        }
    }

    /**
     * 判断热点是否开启
     *
     * @param context
     * @return
     */
    public static boolean isWifiApOpen(Context context) {
        try {
            // BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
            // String deviceName = myDevice.getName();
            // Logc.e("isWifiApOpen: " + deviceName);
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            //通过放射获取 getWifiApState()方法
            Method method = manager.getClass().getDeclaredMethod("getWifiApState");
            //调用getWifiApState() ，获取返回值
            int state = (int) method.invoke(manager);
            //通过放射获取 WIFI_AP的开启状态属性
            Field field = manager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
            //获取属性值
            int value = (int) field.get(manager);
            //判断是否开启
            return state == value;
        } catch (NoSuchMethodException | IllegalAccessException
                | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 无效
     * @param context
     * @return
     * @deprecated
     */
    public static String getWifiApSsid(Context context) {
        try {
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            //拿到getWifiApConfiguration()方法
            Method method = manager.getClass().getDeclaredMethod("getWifiApConfiguration");
            //调用getWifiApConfiguration()方法，获取到 热点的WifiConfiguration
            WifiConfiguration configuration = (WifiConfiguration) method.invoke(manager);
            return configuration.SSID;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }
}
